package com.th.supcom.pds.impl.common.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.carefx.fc.framework.web.gwt.util.FcUtils;
import net.carefx.framework.exception.BusinessException;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.th.supcom.pds.domain.pojo.PdsSupply;
import com.th.supcom.pds.domain.pojo.PhamAttributeInfo;
import com.th.supcom.pds.domain.pojo.PhamBasicInfo;
import com.th.supcom.pds.domain.vo.ExecListVO;
import com.th.supcom.pds.domain.vo.PdsSupplyDetailVO;
import com.th.supcom.pds.domain.vo.PdsSupplyVO;
import com.th.supcom.pds.impl.common.enums.IsNeedCheck;
import com.th.supcom.pds.impl.manager.PhamAttributeInfoManager;
import com.th.supcom.pds.impl.manager.PhamInfoManager;
import com.th.supcom.pds.internal.api.PdsSupplyService;

public final class ServerUitls
{
    private static PhamInfoManager s_phamInfoManager;
    private static PhamAttributeInfoManager s_phamAttributeInfoManager;
    private static PdsSupplyService s_pdsSupplyService;

    public void setPdsSupplyService (PdsSupplyService pdsSupplyService)
    {
        s_pdsSupplyService = pdsSupplyService;
    }

    public void setPhamInfoManager (PhamInfoManager phamInfoManager)
    {
        s_phamInfoManager = phamInfoManager;
    }

    public void setPhamAttributeInfoManager (PhamAttributeInfoManager phamAttributeInfoManager)
    {
        s_phamAttributeInfoManager = phamAttributeInfoManager;
    }

    /**
     * 构造函数私有化
     */
    private ServerUitls ()
    {

    }

    /**
     * 将xml根节点 list转换成对应的，List对象通过FcXStream工具转换成XML的时候根节点的名称是list.
     * 
     * @param root
     */
    public static String convertXMLRoot (String xmlString, String root)
    {
        if (!xmlString.startsWith ("<list>"))
        {
            return xmlString;
        }

        if (!xmlString.endsWith ("</list>"))
        {
            return xmlString;
        }

        String tmpString = xmlString;
        return tmpString.replace ("list", root);
    }

    /**
     * 获取客户端WebService
     * 
     * @param cls
     * @param address
     * @return
     */
    public static Object getWebService (Class < ? > cls, String address)
    {
        JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean ();
        factoryBean.setAddress (address);
        factoryBean.setServiceClass (cls);
        return factoryBean.create ();
    }

    /**
     * 判断是否为晚上
     * 
     * @return
     */
    public static boolean isNight (String date)
    {
        Date now = FcUtils.getCurrentServerDateTimeForServer ();
        DateFormat df = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
        String currentDay = df.format (now).split (" ")[0];
        try
        {
            Date currentNight = df.parse (currentDay + " " + date + ":00");
            if (now.getTime () > currentNight.getTime ())
            {
                return true;
            }
        }
        catch (ParseException e)
        {
            e.printStackTrace ();
        }

        return false;
    }

    public static void findPhamsCosts (List <PdsSupplyDetailVO> pdsSupplyDetailVOs)
    {
        for (PdsSupplyDetailVO pdsSupplyDetailVO : pdsSupplyDetailVOs)
        {
            String phamStdCode = pdsSupplyDetailVO.getPhamStdCode ();
            Map <String, Object> phamMap = new HashMap <String, Object> ();
            phamMap.put ("phamStdCode", phamStdCode);
            PhamBasicInfo phamBasicInfo = s_phamInfoManager.getPhamBasicInfoByMap (phamMap);
            if (phamBasicInfo == null)
            {
                s_logger.error ("药品信息查询异常，药品编码找不到记录。");
                throw new BusinessException ("药品信息查询异常，药品编码找不到记录。");
            }
            Double packagePrice = phamBasicInfo.getRetailPrice ();
            pdsSupplyDetailVO.setPackagePrice (packagePrice);
            pdsSupplyDetailVO.setCosts (packagePrice * pdsSupplyDetailVO.getUnitQty ());
        }
    }

    public static Double getPhamDosePerUnit (String phamStdCode)
    {
        Map <String, Object> phamMap = new HashMap <String, Object> ();
        phamMap.put ("phamStdCode", phamStdCode);
        PhamBasicInfo phamBasicInfo;
        try
        {
            phamBasicInfo = s_phamInfoManager.getPhamBasicInfoByMap (phamMap);
        }
        catch (Exception e)
        {
            s_logger.error ("查询药品信息出现异常，异常信息:{}", new Object[]
            { e });
            throw new BusinessException ("药品信息查询异常，请联系计算机中心。");
        }
        if (phamBasicInfo == null)
        {
            s_logger.error ("药品信息查询异常，药品编码找不到记录。");
            throw new BusinessException ("药品信息查询异常，药品编码找不到记录。");
        }
        return phamBasicInfo.getDosePerUnit ();
    }

    /**
     * 根据药品编码集 查询药品集合是否需要审核(0为不需要审核，1为需要审核)
     * 
     * @param phamStdCode
     * @return add by yzhang
     */
    public static String checkPhamsToxicology (List <PdsSupplyDetailVO> PdsSupplyDetailVOs)
    {
        s_logger.debug ("进入checkPhamsToxicology方法 入参：PdsSupplyDetailVOs", new Object[]
        { PdsSupplyDetailVOs });
        if (CollectionUtils.isEmpty (PdsSupplyDetailVOs))
        {
            throw new BusinessException ("传入药品集合为空！");
        }
        String flag = IsNeedCheck.UnNeed.getEnumCode ();
        for (PdsSupplyDetailVO pdsSupplyDetailVO : PdsSupplyDetailVOs)
        {
            Map <String, Object> map = new HashMap <String, Object> ();
            String phamStdCode = pdsSupplyDetailVO.getPhamStdCode ();
            map.put ("phamStdCode", pdsSupplyDetailVO.getPhamStdCode ());
            List <PhamAttributeInfo> phamAttributeInfos = s_phamAttributeInfoManager.findPhamAttributeInfoListByMap (map);
            if (CollectionUtils.isEmpty (phamAttributeInfos))
            {
                continue;
            }
            if (phamAttributeInfos.size () > 1)
            {
                throw new BusinessException ("数据异常！药品编码：" + phamStdCode + "在药品属性信息表中存在多条记录！");
            }
            PhamAttributeInfo phamAttributeInfo = phamAttributeInfos.get (0);
            if (phamAttributeInfo.getToxicologyProperty () != null && !"9".equals (phamAttributeInfo.getToxicologyProperty ()))
            {
                flag = IsNeedCheck.Need.getEnumCode ();
                return flag;
            }
        }
        return flag;
    }

    /**
     * 检查处方是否收费，收费：true，未收费: false
     * 
     * @param pdsSupply
     * @return add by Zli
     */
    public static boolean checkPrescCharge (PdsSupply pdsSupply)
    {
        s_logger.debug ("调用checkPrescCharge方法，入参：pdsSupply:{}", new Object[]
        { pdsSupply });
        List <PdsSupply> pdsList = null;
        try
        {
            pdsList = s_pdsSupplyService.findPdsSupplyListByExample (pdsSupply);
        }
        catch (Exception e)
        {
            s_logger.error (e.getLocalizedMessage ());
            throw new BusinessException ("检查处方收费出现异常！", e);
        }
        if (pdsList.isEmpty ())
        {
            return false;
        }

        return true;
    }

    /**
     * 是否审核
     * 
     * @param list
     */
    public static void checkFlag (List <PdsSupplyVO> list)
    {
        l: for (PdsSupplyVO pdsSupplyVO : list)
        {
            List <ExecListVO> execListVOs = pdsSupplyVO.getExecList ();
            for (ExecListVO execListVO : execListVOs)
            {
                if ("1".equals (execListVO.getExecAction ()))
                {
                    if ("0".equals (execListVO.getExecResult ()))
                    {
                        pdsSupplyVO.setCheckFlag (IsNeedCheck.UnNeed.getEnumCode ());
                        continue l;
                    }
                    if ("1".equals (execListVO.getExecResult ()))
                    {
                        pdsSupplyVO.setCheckFlag (IsNeedCheck.Need.getEnumCode ());
                        continue l;
                    }
                }
            }
        }
    }

    /** 日志记录器. */
    public static final Logger s_logger = LoggerFactory.getLogger (ServerUitls.class);
    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";

}
